package com.nowcoder.community.controller;

import com.nowcoder.community.entity.*;
import com.nowcoder.community.kafka.EventProducer;
import com.nowcoder.community.service.*;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping(path = "/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发布帖子
     * @param title
     * @param content
     * @return
     */
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUsers();
        if(user == null) {
            return CommunityUtil.getJsonString(403, "用户尚未登录!");
        }
        if(StringUtils.isBlank(title)) {
            return CommunityUtil.getJsonString(406, "需填写帖子标题");
        }
        if(StringUtils.isBlank(content)) {
            return CommunityUtil.getJsonString(407, "需填写帖子内容");
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setType(0);
        discussPost.setScore(0);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        // 将新帖子异步更新到ElasticSearch引擎中
        // 使用kafka消息队列构建异步事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());

        eventProducer.fireEvent(event);

        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPost.getId());

        return CommunityUtil.getJsonString(200, "帖子发表成功!");
    }

    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPostDetail(@PathVariable("discussPostId") int id, Model model, Page page) {
        DiscussPost post = discussPostService.findDiscussPostById(id);
        // 根据用户id得到用户的一些基本信息进行显示
        // 目前解决方案还是多查一次数据库
        // 后续使用redis优化
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);
        model.addAttribute("post", post);
        // 查询帖子的点赞数
        model.addAttribute("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, id));
        // 查询
        // !!!当前登录用户!!!帖子点赞状态
        model.addAttribute("likeStatus",
                    hostHolder.getUsers() == null ?
                            0 : likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_POST, id)
                );

        // 查询帖子评论的分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + id);
        page.setRows(post.getCommentCount());

        List<Comment> commentList = commentService.findCommentByEntity(ENTITY_TYPE_POST, post.getId(), page.getOffSet(), page.getLimit());
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if(commentList != null && !commentList.isEmpty()) {
            for(Comment comment : commentList) {
                Map<String, Object> commentVo = new HashMap<>();
                commentVo.put("comment", comment);
                commentVo.put("user", userService.findUserById(comment.getUserId()));
                // 获取评论点赞数
                commentVo.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId()));
                // 获取当前登陆用户的点赞状态
                commentVo.put("likeStatus",
                        hostHolder.getUsers() == null ?
                                0 : likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_COMMENT, comment.getId())
                );
                // 查询每条评论的评论
                List<Comment> replyList = commentService.findCommentByEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if(replyList != null && !replyList.isEmpty()) {
                    for(Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        replyVo.put("reply", reply);
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        User targetUser = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", targetUser);
                        // 查询对回复的点赞
                        replyVo.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId()));
                        // 查询当前登陆用户对回复的点y赞状态
                        replyVo.put("likeStatus",
                                hostHolder.getUsers() == null ?
                                        0 : likeService.findEntityLikeStatus(hostHolder.getUsers().getId(), ENTITY_TYPE_COMMENT, reply.getId())
                        );
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replies", replyVoList);

                // 查询针对每条评论的回复数量
                int cnt = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", cnt);
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        model.addAttribute("offset",page.getOffSet());
        return "/site/discuss-detail.html";
    }

    // 置顶帖子
    // 异步请求
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setPostTop(int discussPostId) {
        // type类型为1表示帖子置顶
        discussPostService.updateTypeById(discussPostId, 1);

        // 将置顶后的帖子更新到ElasticSearch引擎中
        User user = hostHolder.getUsers();
        Event event = new Event()
                .setTopic(TOPIC_TOP)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPostId);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(0, "帖子置顶成功");
    }

    // 加精帖子
    // 异步请求
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setPostWonderful(int discussPostId) {
        discussPostService.updateStatusById(discussPostId, 1);

        User user = hostHolder.getUsers();
        Event event = new Event()
                .setTopic(TOPIC_WONDERFUL)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPostId);
        eventProducer.fireEvent(event);

        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPostId);

        return CommunityUtil.getJsonString(0, "帖子加精成功");
    }

    // 删除帖子
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String deletePost(int discussPostId) {
        discussPostService.updateStatusById(discussPostId, 2);

        User user = hostHolder.getUsers();
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPostId);

        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(0, "删除帖子成功");
    }
}
